package com.mariusz.utils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.mariusz.data.dto.Payment;
import com.mariusz.data.dto.Rentier;

public class PaymentsCalculator {

	public List<Payment> calculate(Rentier rentier){
		switch(rentier.getPaymentInterval()){
			case WEEKLY: return calculateWeekly(rentier,1); 
			case TWO_WEEK: return calculateWeekly(rentier,2);
			case THREE_WEEKLY: return calculateWeekly(rentier,3);
			case FOUR_WEEKLY: return calculateWeekly(rentier,4);
			case MONTHLY: return calculateMonthly(rentier);
			default: return null;
		}
	}
	
	private List<Payment> calculateWeekly(Rentier rentier, int weeks){
		List<Payment> payments = new ArrayList<Payment>();
		Calendar begin = Calendar.getInstance();
		begin.setTime(rentier.getContractBeginDate());
		Calendar end = Calendar.getInstance();
		end.setTime(rentier.getContractEndDate());
	
		do{
			Payment payment = new Payment();
			payment.setAmount(rentier.getPaymentAmount()*weeks);
			payment.setPaymentDate(begin.getTime());
			payment.setPaied(false);
			payment.setNotes("");
			begin.add(Calendar.WEEK_OF_YEAR, weeks);
			payments.add(payment);
		}while(begin.before(end));
		return payments;
		
	}
	
	private List<Payment> calculateMonthly(Rentier rentier){
		List<Payment> payments = new ArrayList<Payment>();
		Calendar begin = Calendar.getInstance();
		begin.setTime(rentier.getContractBeginDate());
		Calendar end = Calendar.getInstance();
		end.setTime(rentier.getContractEndDate());
		//Monthly payments based on weekly amount.
		Double amount = (rentier.getPaymentAmount()*52)/12;
		amount = (double) (Math.round(amount*100)/100.00);
		
		do{
			Payment payment = new Payment();
			payment.setAmount(amount);
			payment.setPaymentDate(begin.getTime());
			payment.setPaied(false);
			payment.setNotes("");
			begin.add(Calendar.MONTH, 1);
			payments.add(payment);
		}while(begin.before(end));
		
		return payments;
	}
}
